"""
USC 医院管理系统 - FastAPI 版本

这是使用 FastAPI + PostgreSQL 重构的医院管理系统后端。

主要功能：
- 医生认证和管理
- 患者信息管理
- 病历管理
- 表单模板管理
- 统计数据展示

技术栈：
- FastAPI: Web 框架
- PostgreSQL: 数据库
- SQLAlchemy: ORM
- Pydantic: 数据验证
- JWT: 身份认证
"""
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError
from starlette.exceptions import HTTPException as StarletteHTTPException

from core.config import settings
from api.v1 import auth, doctors, patients, medical_records, templates, statistics, notifications, template_data

# 创建 FastAPI 应用
app = FastAPI(
    title=settings.APP_NAME,
    version=settings.APP_VERSION,
    description="USC 医院管理系统后端 API",
    docs_url="/docs",
    redoc_url="/redoc",
    openapi_url="/openapi.json"
)

# 配置 CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.CORS_ORIGINS,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


# 异常处理器
@app.exception_handler(StarletteHTTPException)
async def http_exception_handler(request, exc):
    """处理 HTTP 异常"""
    return JSONResponse(
        status_code=exc.status_code,
        content={
            "code": 1,
            "message": exc.detail,
            "data": None
        }
    )


@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request, exc):
    """处理数据验证异常"""
    errors = []
    for error in exc.errors():
        field = " -> ".join(str(loc) for loc in error["loc"])
        message = error["msg"]
        errors.append(f"{field}: {message}")
    
    return JSONResponse(
        status_code=422,
        content={
            "code": 1,
            "message": "数据验证失败: " + "; ".join(errors),
            "data": {"errors": exc.errors()}
        }
    )


@app.exception_handler(Exception)
async def general_exception_handler(request, exc):
    """处理通用异常"""
    import traceback
    if settings.DEBUG:
        # 开发环境显示详细错误
        return JSONResponse(
            status_code=500,
            content={
                "code": 1,
                "message": f"服务器错误: {str(exc)}",
                "data": {"traceback": traceback.format_exc()}
            }
        )
    else:
        # 生产环境隐藏错误细节
        return JSONResponse(
            status_code=500,
            content={
                "code": 1,
                "message": "服务器内部错误",
                "data": None
            }
        )


# 根路由
@app.get("/", tags=["Root"])
async def root():
    """API 根路径"""
    return {
        "code": 0,
        "message": "USC 医院管理系统 API",
        "data": {
            "version": settings.APP_VERSION,
            "docs": "/docs",
            "redoc": "/redoc"
        }
    }


# 健康检查
@app.get("/health", tags=["Health"])
async def health_check():
    """健康检查接口"""
    return {
        "code": 0,
        "message": "服务正常运行",
        "data": {
            "status": "healthy",
            "version": settings.APP_VERSION
        }
    }


# 注册路由
app.include_router(
    auth.router,
    prefix="/api/auth",
    tags=["认证"]
)

app.include_router(
    doctors.router,
    prefix="/api/doctors",
    tags=["医生管理"]
)

app.include_router(
    notifications.router,
    prefix="/api/notifications",
    tags=["通知管理"]
)

# app.include_router(
#     patients.router,
#     prefix="/api/patients",
#     tags=["患者管理"]
# )

#兼容前端的旧路径：/api/patients/patients
app.include_router(
    patients.router,
    prefix="/api/patients/patients",
    tags=["患者管理-兼容路径"],
    #include_in_schema=False  # 不在 API 文档中显示
)

app.include_router(
    medical_records.router,
    prefix="/api/medical-records",
    tags=["病历管理"]
)

app.include_router(
    templates.router,
    prefix="/api/form-templates",
    tags=["表单模板"]
)

app.include_router(
    template_data.router,
    prefix="/api/template-data",
    tags=["模板数据"]
)

app.include_router(
    statistics.router,
    prefix="/api/statistics",
    tags=["统计数据"]
)


# 启动事件
@app.on_event("startup")
async def startup_event():
    """应用启动时执行"""
    print(f"🚀 {settings.APP_NAME} v{settings.APP_VERSION} 启动中...")
    print(f"📝 API 文档: http://{settings.HOST}:{settings.PORT}/docs")
    print(f"🗄️  数据库: PostgreSQL")
    print(f"🔧 环境: {'开发' if settings.DEBUG else '生产'}")


# 关闭事件
@app.on_event("shutdown")
async def shutdown_event():
    """应用关闭时执行"""
    print(f"👋 {settings.APP_NAME} 正在关闭...")


if __name__ == "__main__":
    import uvicorn
    
    uvicorn.run(
        "main:app",
        host=settings.HOST,
        port=settings.PORT,
        reload=settings.DEBUG,
        log_level="info"
    )

